package cn.hist.hfp.controller;

import cn.hist.hfp.RoleType;
import cn.hist.hfp.entity.Comment;
import cn.hist.hfp.service.CommentService;
import cn.hist.hfp.util.Authentication;
import cn.hist.hfp.util.MyResponse;
import cn.hist.hfp.vo.CommentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {

    private final
    CommentService commentService;

    private final
    Authentication authentication;

    private final
    MyResponse<Comment> myResponse;

    @Autowired
    public CommentController(CommentService commentService, Authentication authentication, MyResponse<Comment> myResponse) {
        this.commentService = commentService;
        this.authentication = authentication;
        this.myResponse = myResponse;
    }

    @PostMapping
    public ResponseEntity<Comment> create(@RequestBody Comment comment, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.USER, RoleType.MANAGER);
        return myResponse.response(201, authentication.refreshToken(token), commentService.create(comment));
    }

    @GetMapping("/{id}")
    public Comment findOne(@PathVariable int id) {
        return commentService.findOne(id);
    }

    @GetMapping("/page/stray/{id}/{page}")
    public List<CommentVO> findSomeByStray(@PathVariable int page, @PathVariable int id) {
        return commentService.findSomeByStray(page, id);
    }

    @GetMapping("/page/user/{id}/{page}")
    public List<CommentVO> findSomeByUser(@PathVariable int page, @PathVariable int id) {
        return commentService.findSomeByUser(page, id);
    }

    @GetMapping("/page/stray")
    public int numberOfPagesSortByStray(int id) {
        return commentService.numberOfPagesSortByStray(id);
    }

    @GetMapping("/page/user")
    public int numberOfPagesSortByUser(int id) {
        return commentService.numberOfPagesSortByUser(id);
    }

    @PutMapping
    public ResponseEntity<Comment> update(@RequestBody Comment comment, @RequestHeader int user_id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.USER, RoleType.MANAGER);
        return myResponse.response(200, authentication.refreshToken(token), commentService.update(comment, user_id));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity delete(@PathVariable int id, @RequestHeader int user_id, @RequestHeader String token) {
        authentication.permissionCheck(token, RoleType.USER, RoleType.MANAGER);
        MyResponse<Integer> myResponse = new MyResponse<>();
        return myResponse.response(200, authentication.refreshToken(token), commentService.delete(id, user_id));
    }
}
